define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'knowbase'], function ($, undefined, Backend, Table, Form, Knowbase) {

    var Controller = {
        refreshSelect: {
            'admin_id': false,
            'admin_ids': false,
            'auth_group_ids': false,
        },
        oldData: {
            'admin_id': '',
            'admin_ids': '',
            'auth_group_ids': '',
        },
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'knowbase/project/index' + location.search,
                    add_url: 'knowbase/project/add',
                    edit_url: 'knowbase/project/edit',
                    del_url: 'knowbase/project/del',
                    multi_url: 'knowbase/project/multi',
                    import_url: 'knowbase/project/import',
                    table: 'knowbase_project',
                }
            });

            var table = $("#table");
            var buttons = [
            //     {
            //     name: 'dragsort',
            //     icon: 'fa fa-arrows',
            //     title: __('Drag to sort'),
            //     extend: 'data-toggle="tooltip"',
            //     classname: 'btn btn-xs btn-primary btn-dragsort',
            //     hidden: function (row) {
            //         return false;
            //     }
            // },
                {
                name: 'look',
                icon: 'fa fa-eye',
                title: __('tips_btn_look'),
                //extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-info  btn-addtabs',
                url: function (row) {
                    return 'knowbase/project_page/index?knowbase_project_id=' + row.id;
                },
            }, {
                name: 'link',
                icon: 'fa fa-link',
                title: __('tips_btn_visit'),
                extend: 'target="_blank"',
                classname: 'btn btn-xs btn-default',
                url: function (row) {
                    return Config.url_knowbase_project.replace('{0}',row.id);
                },
                hidden: function (row) {
                    if (row.status == 0) {
                        return true;
                    }
                    return false;
                }
            }, {
                name: 'edit',
                icon: 'fa fa-pencil',
                title: __('Edit'),
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-success btn-editone'
            },
                {
                name: 'del',
                icon: 'fa fa-trash',
                title: __('Del'),
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-danger btn-delone',
                hidden: function (row) {
                    if (row.archive_switch == 1) {
                        return true;
                    } else {
                        return false;
                    }
                }
            },
            //     {
            //     name: 'clone',
            //     icon: 'fa fa-copy',
            //     title: __('btn_clone'),
            //     classname: 'btn btn-xs btn-warning btn-ajax btn-cloneone',
            //     url: 'knowbase/project/cloneone',
            //     success: function (data, ret) {
            //         if (ret.code && ret.code == 1) {
            //             table.bootstrapTable('refresh');
            //         }
            //     },
            //     error: function (data, ret) {
            //         Layer.alert(ret.msg);
            //         return false;
            //     },
            //     hidden: function (row) {
            //         if (!Config.clone) {
            //             return true;
            //         }
            //         return false;
            //     }
            // }
            ];

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: false,
                searchFormVisible: true,
                fixedRightNumber: 1,
                onClickCell: function (field, value, row, $element) {
                    // 记录原先的选择
                    Controller.oldData.admin_ids = $('#c-admin_ids').val();
                    if (field == 'admin_ids') {
                        Controller.refreshSelect.admin_ids = true;
                    }

                    Controller.oldData.auth_group_ids = $('#c-auth_group_ids').val();
                    if (field == 'auth_group_ids') {
                        Controller.refreshSelect.auth_group_ids = true;
                    }

                    if (field == 'admin_id') {
                        Controller.refreshSelect.admin_id = true;
                    }

                },
                onCommonSearch: function (params) {
                    // 请求前触发
                    if (Controller.refreshSelect.admin_ids) {
                        var new_admin_ids = $('#c-admin_ids').val();
                        var old_admin_ids = Controller.oldData.admin_ids;
                        if (old_admin_ids != '') {
                            old_admin_ids = old_admin_ids.split(',');
                            old_admin_ids.push(new_admin_ids);
                            old_admin_ids = Knowbase.unique(old_admin_ids).join(',');
                        } else {
                            old_admin_ids = new_admin_ids;
                        }
                        $('#c-admin_ids').val(old_admin_ids);
                    }

                    if (Controller.refreshSelect.auth_group_ids) {
                        var new_auth_group_ids = $('#c-auth_group_ids').val();
                        var old_auth_group_ids = Controller.oldData.auth_group_ids;
                        if (old_auth_group_ids != '') {
                            old_auth_group_ids = old_auth_group_ids.split(',');
                            old_auth_group_ids.push(new_auth_group_ids);
                            old_auth_group_ids = Knowbase.unique(old_auth_group_ids).join(',');
                        } else {
                            old_auth_group_ids = new_auth_group_ids;
                        }
                        $('#c-auth_group_ids').val(old_auth_group_ids);

                    }

                },
                onRefresh: function (params) {
                    // 请求后触发
                    if (Controller.refreshSelect.admin_ids) {
                        $('#c-admin_ids').selectPageRefresh();
                        Controller.refreshSelect.admin_ids = false;
                    }

                    if (Controller.refreshSelect.auth_group_ids) {
                        $('#c-auth_group_ids').selectPageRefresh();
                        Controller.refreshSelect.auth_group_ids = false;
                    }

                    if (Controller.refreshSelect.admin_id) {
                        $('#c-admin_id').selectPageRefresh();
                        Controller.refreshSelect.admin_id = false;
                    }

                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'title',
                            title: __('Title'),
                            operate: 'LIKE',
                            formatter: function (value, row, index) {
                                if (row.archive_switch == 1) {
                                    return row.title + '【' + __('archive') + '】';
                                } else {
                                    return row.title;
                                }
                            }
                        },
                       // {field: 'identify', title: __('Identify')},
                        //{field: 'description', title: __('Description'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {
                        //     field: 'image',
                        //     title: __('Image'),
                        //     operate: false,
                        //     events: Table.api.events.image,
                        //     formatter: Table.api.formatter.image
                        // },
                       // {field: 'views', title: __('Views'), operate: false},
                        //{field: 'tags', title: __('Tags'), operate: 'LIKE', formatter: Table.api.formatter.flag},
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {"0": __('Status 0'), "1": __('Status 1')},
                            formatter: Table.api.formatter.status
                        },
                        // {
                        //     field: 'admin_id', title: __('Admin_id'), searchList: function (column) {
                        //         return '<input id="c-admin_id"  data-source="auth/admin/index" ' +
                        //             'data-order-by="id" data-multiple="false" ' +
                        //             'data-page-size="20"  ' +
                        //             'data-search-field="username" ' +
                        //             'data-field="username" ' +
                        //             'data-pagination="true" ' +
                        //             'class="form-control selectpage" ' +
                        //             'name="admin_id" type="text" value="">';
                        //     }, formatter: Controller.api.formatter.normal, display: function (row) {
                        //         return row.admin ? row.admin.username : "-";
                        //     }
                        // },
                        // {
                        //     field: 'access_type',
                        //     title: __('Access_type'),
                        //     searchList: {"0": __('Access_type 0'), "1": __('Access_type 1'), "2": __('Access_type 2')},
                        //     formatter: Table.api.formatter.normal
                        // },
                        // {
                        //     field: 'auth_group_ids',
                        //     title: __('Auth_group_ids'),
                        //     operate: "IN",
                        //     table: table,
                        //     class: 'autocontent',
                        //     formatter: Controller.api.formatter.flag,
                        //     display: function (row, index) {
                        //         if (row.groups[index] && row.groups[index].auth_group) {
                        //             return row.groups[index].auth_group.name;
                        //         } else {
                        //             return '';
                        //         }
                        //     },
                        //     getValue: function (row, index) {
                        //         if (row.groups[index] && row.groups[index].auth_group) {
                        //             return row.groups[index].auth_group.id;
                        //         } else {
                        //             return '';
                        //         }
                        //     },
                        //     searchList: function (column) {
                        //         return '<input id="c-auth_group_ids"  data-source="knowbase/group_new/index" ' +
                        //             'data-order-by="id" data-multiple="true" ' +
                        //             'data-page-size="20"  ' +
                        //             'data-search-field="id" ' +
                        //             'data-field="name" ' +
                        //             'data-pagination="true" ' +
                        //             'class="form-control selectpage" ' +
                        //             'name="auth_group_ids" type="text" value="">';
                        //     }
                        // },
                        // {
                        //     field: 'admin_ids',
                        //     title: __('Admin_ids'),
                        //     operate: "IN",
                        //     table: table,
                        //     class: 'autocontent',
                        //     formatter: Controller.api.formatter.flag,
                        //     display: function (row, index) {
                        //         if (row.auths[index] && row.auths[index].auth) {
                        //             return row.auths[index].auth.username;
                        //         } else {
                        //             return '';
                        //         }
                        //     },
                        //     getValue: function (row, index) {
                        //         if (row.auths[index] && row.auths[index].auth) {
                        //             return row.auths[index].auth.id;
                        //         } else {
                        //             return '';
                        //         }
                        //     },
                        //     searchList: function (column) {
                        //         return '<input id="c-admin_ids"  data-source="auth/admin/selectpage" ' +
                        //             'data-order-by="id" data-multiple="true" ' +
                        //             'data-page-size="20"  ' +
                        //             'data-search-field="id" ' +
                        //             'data-field="username" ' +
                        //             'data-pagination="true" ' +
                        //             'class="form-control selectpage" ' +
                        //             'name="admin_ids" type="text" value="">';
                        //     }
                        // },
                        //{field: 'weigh', title: __('Weigh'), operate: false},
                        //{field: 'password', title: __('Password'), operate: 'LIKE'},
                        //{field: 'user_group_ids', title: __('User_group_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        //{field: 'archive_switch', title: __('Archive_switch'), searchList: {"1":__('Yes'),"0":__('No')}, table: table, formatter: Table.api.formatter.toggle},
                        // {
                        //     field: 'title',
                        //     title: __('Title'),
                        //     operate: false,
                        //     formatter: function (value, row, index) {
                        //         if (row.archive_switch == 1) {
                        //             return row.title + '【' + __('archive') + '】';
                        //         } else {
                        //             return row.title;
                        //         }
                        //     }
                        // },
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        //{field: 'archivetime', title: __('Archivetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $('.btn-sitemap').click(function (e) {
                e.preventDefault();
                Fast.api.ajax({
                    url: 'knowbase/project/sitemap',
                    type: 'post'
                }, function (data, ret) {
                });
            });
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'knowbase/project/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'knowbase/project/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    confirm: __('sure_delete_projects'),
                                    url: 'knowbase/project/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        export: function () {
            Controller.api.bindevent();
            this.initListen();
        },
        export_html: function () {
            Controller.api.bindevent();
            this.initListen();
        },
        add: function () {
            Controller.api.bindevent();
            this.initListen();
        },
        edit: function () {
            Controller.api.bindevent();
            this.initListen();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                flag: function (value, row, index) {
                    var that = this;
                    value = value == null || value.length === 0 ? '' : value.toString();
                    var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
                    //如果字段列有定义custom
                    if (typeof this.custom !== 'undefined') {
                        colorArr = $.extend(colorArr, this.custom);
                    }
                    var field = this.field;
                    if (typeof this.customField !== 'undefined' && typeof row[this.customField] !== 'undefined') {
                        value = row[this.customField];
                        field = this.customField;
                    }

                    if (typeof that.searchList === 'object' && typeof that.custom === 'undefined') {
                        var i = 0;
                        var searchValues = Object.values(colorArr);
                        $.each(that.searchList, function (key, val) {
                            if (typeof colorArr[key] == 'undefined') {
                                colorArr[key] = searchValues[i];
                                i = typeof searchValues[i + 1] === 'undefined' ? 0 : i + 1;
                            }
                        });
                    }

                    //渲染Flag
                    var html = [];
                    var arr = value != '' ? value.split(',') : [];
                    var color, display, label;
                    $.each(arr, function (i, value) {
                        value = value == null || value.length === 0 ? '' : value.toString();
                        if (value == '')
                            return true;
                        color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                        display = typeof that.searchList !== 'undefined' && typeof that.searchList[value] !== 'undefined' ? that.searchList[value] : __(value.charAt(0).toUpperCase() + value.slice(1));
                        if (typeof that.display === 'function') {
                            display = that.display(row, i);
                            if (display == '') {
                                return true;
                            }
                        }

                        if (typeof that.getValue === 'function') {
                            value = that.getValue(row, i);
                        }

                        label = '<span class="label label-' + color + '">' + display + '</span>';
                        if (that.operate) {
                            html.push('<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + field + '" data-value="' + value + '">' + label + '</a>');
                        } else {
                            html.push(label);
                        }
                    });
                    return html.join(' ');
                },
                normal: function (value, row, i) {
                    var that = this;
                    var colorArr = ["primary", "success", "danger", "warning", "info", "gray", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];
                    var custom = {};
                    if (typeof this.custom !== 'undefined') {
                        custom = $.extend(custom, this.custom);
                    }
                    value = value == null || value.length === 0 ? '' : value.toString();
                    var keys = typeof this.searchList === 'object' ? Object.keys(this.searchList) : [];
                    var index = keys.indexOf(value);
                    var color = value && typeof custom[value] !== 'undefined' ? custom[value] : null;
                    var display = index > -1 ? this.searchList[value] : null;
                    var icon = typeof this.icon !== 'undefined' ? this.icon : null;
                    if (!color) {
                        color = index > -1 && typeof colorArr[index] !== 'undefined' ? colorArr[index] : 'primary';
                    }

                    if (!display) {
                        display = __(value.charAt(0).toUpperCase() + value.slice(1));
                    }
                    if (typeof that.display === 'function') {
                        display = that.display(row);
                        if (display == '-') {
                            return '-';
                        }
                    }
                    var html = '<span class="text-' + color + '">' + (icon ? '<i class="' + icon + '"></i> ' : '') + display + '</span>';
                    if (this.operate != false) {
                        html = '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + this.field + '" data-value="' + value + '">' + html + '</a>';
                    }
                    return html;
                }
            }
        },
        initListen: function () {
            $(document).on("change", "#c-access_type", function (e) {
                //变更后的回调事件
                var value = $(this).val();
                $('.password').hide();
                $('.user_group_ids').hide();
                if (value == 1) {
                    $('.password').show();
                } else if (value == 2) {
                    $('.user_group_ids').show();
                }

            });

            $('.btn-random').click(function (e) {
                $(this).parent().parent().find('input').val(Knowbase.getRandomStr(32));
            });

            $('#export').click(function (e) {
                e.preventDefault();
                var that = this;
                $(this).addClass('btn-disabled').addClass('disabled');
                $.post('knowbase/project/export', {'knowbase_project_id': Fast.api.query('knowbase_project_id')}, function (data) {
                    if (data.code == 0) {
                        Layer.alert(data.msg);
                    } else {
                        $('button[data-type=pdf]').trigger('click');
                    }
                    setTimeout(function () {
                        $(that).removeClass('btn-disabled').removeClass('disabled');
                    }, 5000);
                });
            });

            $('#exportHtml').click(function (e) {
                e.preventDefault();
                var that = this;
                $(this).addClass('btn-disabled').addClass('disabled');
                $.post('knowbase/project/export_html', {'knowbase_project_id': Fast.api.query('knowbase_project_id')}, function (data) {
                    if (data.code == 0) {
                        Layer.alert(data.msg);
                    } else {
                        window.cdn = 'https://unpkg.com/vditor';
                        $('button[data-type=html]').trigger('click');
                    }
                    setTimeout(function () {
                        $(that).removeClass('btn-disabled').removeClass('disabled');
                    }, 5000);
                });
            });
            
        }
    };
    return Controller;
});
